<template>
  <div>
    <el-row>
      <el-col :span="6">
        <el-tag style="font-size: 20px">系统角色</el-tag>
        <div>
          <el-tree
            :data="roles"
            :highlight-current="true"
            @node-click="handleNodeClick"
          />
        </div>
        <div>
          <el-button v-if="checkPermission(rolePageRole.rolePage_delete)" type="failure" plain @click="handleDeleteRole">删除角色</el-button>
        </div>
        <div>
          <el-button v-if="checkPermission(rolePageRole.rolePage_create)" type="success" plain @click="createRoleDialogVisible = true">新增角色</el-button>
        </div>
        <!--  add  -->
        <el-dialog title="添加角色" :visible.sync="createRoleDialogVisible">
          <el-form ref="dataForm" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
            <el-form-item label="角色名称">
              <el-input v-model="addRole.roleName" />
            </el-form-item>
            <el-form-item label="描述">
              <el-input
                v-model="addRole.roleDesc"
                type="textarea"
                :rows="2"
                placeholder="请输入描述信息"
              />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="createRoleDialogVisible = false">
              Cancel
            </el-button>
            <el-button @click="handleCreateRoleCommit">
              Ok
            </el-button>
          </div>
        </el-dialog>
      </el-col>
      <el-col :span="6">
        <el-tag style="font-size: 20px">角色授权资源</el-tag>
        <el-tree
          ref="ResourceTree"
          :data="resources.pages"
          :default-checked-keys="resources.checkedIds"
          show-checkbox
          default-expand-all
          node-key="id"
          highlight-current
          @check-change="canRollbackModify = true"
        />
        <div>
          <el-button v-if="checkPermission(authorizePageRole.authorizePage_update)" type="success" plain @click="rollbackModify">撤销修改</el-button>
        </div>
        <div>
          <el-button v-if="checkPermission(authorizePageRole.authorizePage_update)" type="success" plain @click="handleModify">提交修改</el-button>
        </div>
      </el-col>
      <el-col :span="6">
        <el-tag style="font-size: 20px">授权用户列表</el-tag>
        <div>
          <el-tree
            ref="tree"
            :data="users"
            default-expand-all
            node-key="id"
            highlight-current
            :props="userProps"
            @node-click="handleUserTreeNodeClick"
          />
        </div>
        <div>
          <el-button v-if="checkPermission(authorizePageRole.authorizePage_update)" type="success" plain @click="handleWithddralUserRole">移除选中用户</el-button>
        </div>
      </el-col>
      <el-col v-if="checkPermission(authorizePageRole.authorizePage_update)" :span="6">
        <el-tag style="font-size: 20px">其他操作列表</el-tag>
        <el-link type="primary">选择用户授予该角色</el-link>
        <el-select v-model="readyToAuthorizeUserId" placeholder="请选择">
          <el-option
            v-for="item in allUser"
            :key="item.userId"
            :label="item.name"
            :value="item.userId"
          />
        </el-select>
        <div>
          <el-button type="success" plain @click="handleAuthorizeUserRole">角色授予</el-button>
        </div>
      </el-col>
    </el-row>
    <el-divider />
  </div>
</template>

<script>

import { addRole, deleteRole, fetchPageRolesByPageName } from '@/api/role'
import { getAllInTreeNodeTemplate } from '@/api/rolePage/rolePageApi'
import {
  authorizeUserRole,
  changeRolePermission,
  getAllResourceAndAllOptions,
  getAllUserByRoleId,
  getPermissionIdsByRoleId
} from '@/api/authorize/authorizePageApi'
import { fetchList } from '@/api/user/user'
import checkPermission from '@/utils/permission'

export default {
  inject: ['reload'],
  data() {
    return {
      roles: [{
        label: '系统角色'
      }],
      resources: {
        pages: [],
        activeName: 'userManage',
        checkedIds: []
      },
      users: [{ id: 1, name: '超级管理员' }],
      userProps: {
        label: 'name'
      },
      selectedRoleId: '',
      createRoleDialogVisible: false,
      addRole: { roleName: '', roleDesc: '' },
      readyToAuthorizeUserId: '',
      allUser: [{ userId: '', name: '' }],
      readyToWithdralAuthorizeUserId: '',
      canRollbackModify: false,
      authorizePageRole: {
        authorizePage_retrieve: ['admin'],
        authorizePage_update: ['admin']
      },
      rolePageRole: {
        rolePage_retrieve: ['admin'],
        rolePage_update: ['admin'],
        rolePage_delete: ['admin'],
        rolePage_create: ['admin']
      }
    }
  },
  async created() {
    await this.initialize()
  },
  methods: {
    checkPermission,
    rollbackModify() {
      const h = this.$createElement
      console.log(this.canRollbackModify)
      if (!this.canRollbackModify) {
        this.$notify({
          title: '撤销修改',
          message: h('i', { style: 'color: teal' }, '撤销失败，未发生修改或已提交任务')
        })
        return
      }
      this.canRollbackModify = false
      this.$refs.ResourceTree.setCheckedKeys(this.resources.checkedIds)
      this.$notify({
        title: '撤销修改',
        message: h('i', { style: 'color: teal' }, '成功撤销操作')
      })
    },
    handleUserTreeNodeClick(data) {
      this.readyToWithdralAuthorizeUserId = data.userId
      console.log('select user id: ' + data.userId)
    },
    handleWithddralUserRole() {
      if (this.readyToWithdralAuthorizeUserId === '') {
        window.alert('请选择用户')
        return
      } else if (this.selectedRoleId === '') {
        window.alert('请选择角色')
        return
      }
      authorizeUserRole({
        'userId': this.readyToWithdralAuthorizeUserId,
        'roleId': this.selectedRoleId,
        'optCode': 0 // >0 表示授予
      }).then(response => {
        console.log('sucess')
        const h = this.$createElement
        this.$notify({
          title: '撤销用户角色',
          message: h('i', { style: 'color: teal' }, '撤销成功')
        })
      })
    },
    handleAuthorizeUserRole() {
      if (this.readyToAuthorizeUserId === '') {
        window.alert('请选择用户')
        return
      } else if (this.selectedRoleId === '') {
        window.alert('请选择角色')
        return
      }
      console.log(this.readyToAuthorizeUserId)
      authorizeUserRole({
        'userId': this.readyToAuthorizeUserId,
        'roleId': this.selectedRoleId,
        'optCode': 1 // >0 表示授予
      }).then(response => {
        console.log('sucess')
        const h = this.$createElement
        this.$notify({
          title: '授予用户角色',
          message: h('i', { style: 'color: teal' }, '授予成功')
        })
      })
    },
    handleModify() {
      console.log(this.$refs.ResourceTree.getCheckedKeys())
      var params = new URLSearchParams()
      params.append('roleId', this.selectedRoleId)
      params.append('permissionIds', this.$refs.ResourceTree.getCheckedKeys())
      changeRolePermission(params).then(response => {
        const h = this.$createElement
        this.$notify({
          title: '修改角色权限',
          message: h('i', { style: 'color: teal' }, '操作成功')
        })
        this.canRollbackModify = false
      })
    },
    handleDeleteRole() {
      console.log('delete role :' + this.selectedRoleId)
      if (this.selectedRoleId in [1, 2, 3]) {
        const h = this.$createElement
        this.$notify({
          title: '删除角色',
          message: h('i', { style: 'color: teal' }, '操作失败，受保护角色')
        })
        return
      }
      deleteRole({ 'roleId': this.selectedRoleId }).then(response => {
        const h = this.$createElement
        this.$notify({
          title: '删除角色',
          message: h('i', { style: 'color: teal' }, '操作成功')
        })
        getAllInTreeNodeTemplate().then(response => {
          this.roles = []
          for (const i in response.data) {
            this.roles.push(response.data[i])
          }
        })
      })
    },
    handleNodeClick(data) { // 选择角色
      this.selectedRoleId = data.id
      this.readyToWithdralAuthorizeUserId = ''
      getAllUserByRoleId({ 'roleId': data.id }).then(response => {
        this.users = []
        const data = response.data.items
        for (const i in data) {
          this.users.push(data[i])
        }
      })
      getPermissionIdsByRoleId({ 'roleId': data.id }).then(response => {
        this.resources.checkedIds = []
        this.$refs.ResourceTree.setCheckedKeys([])
        for (const i in response.data) {
          this.resources.checkedIds.push(response.data[i])
        }
        console.log(this.resources.checkedIds)
      })
    },
    handlePageClick(data) {
      console.log(data)
    },
    async initialize() {
      await fetchPageRolesByPageName('userPage').then(response => {
        this.pageRoles = response.data
        console.log('authorize page initialize role over')
        console.log(this.pageRoles)
      })
      getAllInTreeNodeTemplate().then(response => {
        this.roles = response.data
      })
      getAllResourceAndAllOptions().then(response => {
        this.resources.pages = response.data
        console.log(this.resources)
      })
      fetchList().then(response => {
        this.allUser = response.data.items
        console.log(this.users)
      })
      await fetchPageRolesByPageName('authorizePage').then(response => {
        this.authorizePageRole = response.data
        console.log(this.authorizePageRole)
        console.log(response.data)
      })
      // rolePageRole
      await fetchPageRolesByPageName('rolePage').then(response => {
        this.rolePageRole = response.data
        console.log('-----------------')
        console.log(this.rolePageRole)
        console.log(response.data)
        console.log('-----------------')
      })
    },
    handleCreateRoleCommit() {
      addRole(this.addRole).then(response => {
        this.addRole.roleName = ''
        this.addRole.roleDesc = ''
        this.createRoleDialogVisible = false
      }).then(response => {
        const h = this.$createElement
        this.$notify({
          title: '添加角色',
          message: h('i', { style: 'color: teal' }, '成功添加角色')
        })
        fetchList().then(response => {
          this.allUser = response.data.items
          getAllInTreeNodeTemplate().then(response => {
            this.roles = []
            for (const i in response.data) {
              this.roles.push(response.data[i])
            }
          })
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
